<template>
  <view class="unlock-modal" v-if="visible">
    <view class="unlock-modal-mask" @click.stop="closeModal"></view>
    <view class="unlock-modal-content">
      <view class="unlock-modal-header">
        <text class="unlock-modal-title">{{ unlockConfig.title || '解锁功能' }}</text>
        <text class="tn-icon-close unlock-modal-close" @click="closeModal"></text>
      </view>

      <view class="unlock-modal-body">
        <text class="unlock-icon tn-icon-unlock-fill"></text>
        <text class="unlock-desc">{{ unlockConfig.description || '通过完成任务解锁功能' }}</text>

        <view class="unlock-options">
          <!-- VIP解锁 -->
          <view class="unlock-option vip-option" @click="showVipModal" v-if="unlockConfig.vip.enabled">
            <view class="option-content">
              <text class="tn-icon-vip-fill option-icon"></text>
              <view class="option-text">
                <text class="option-title">开通会员</text>
                <text class="option-desc">{{unlockConfig.vip.description || '畅享无限私信'}}</text>
              </view>
            </view>
            <text class="tn-icon-right option-arrow"></text>
          </view>

          <!-- 激励视频解锁 -->
          <view class="unlock-option" @click="unlockByVideo" v-if="unlockConfig.video.enabled">
            <view class="option-content">
              <text class="tn-icon-video-fill option-icon"></text>
              <view class="option-text">
                <text class="option-title">看广告解锁</text>
                <text class="option-desc">今日剩余: {{videoUnlockRemaining}}/{{unlockConfig.video.dailyLimit}}</text>
              </view>
            </view>
            <text class="tn-icon-right option-arrow"></text>
          </view>

          <!-- 分享解锁 -->
          <view class="unlock-option" v-if="unlockConfig.share.enabled">
            <!-- #ifdef MP-WEIXIN -->
            <button class="unlock-option-button" open-type="share" @tap="prepareShare">
              <view class="option-content">
                <text class="tn-icon-share option-icon"></text>
                <view class="option-text">
                  <text class="option-title">分享解锁</text>
                  <text class="option-desc">今日剩余: {{shareUnlockRemaining}}/{{unlockConfig.share.dailyLimit}}</text>
                </view>
              </view>
              <text class="tn-icon-right option-arrow"></text>
            </button>
            <!-- #endif -->

            <!-- #ifndef MP-WEIXIN -->
            <view class="unlock-option" @tap="unlockByShare">
              <view class="option-content">
                <text class="tn-icon-share option-icon"></text>
                <view class="option-text">
                  <text class="option-title">分享解锁</text>
                  <text class="option-desc">今日剩余: {{shareUnlockRemaining}}/{{unlockConfig.share.dailyLimit}}</text>
                </view>
              </view>
              <text class="tn-icon-right option-arrow"></text>
            </view>
            <!-- #endif -->
          </view>

          <!-- 扩展的其他解锁选项，可通过配置动态添加 -->
          <view class="unlock-option"
                v-for="(option, index) in unlockConfig.extraOptions"
                :key="index"
                @click="handleExtraOptionClick(option)"
                :class="option.className">
            <view class="option-content">
              <text :class="['option-icon', option.iconClass]"></text>
              <view class="option-text">
                <text class="option-title">{{option.title}}</text>
                <text class="option-desc">{{option.description}}</text>
              </view>
            </view>
            <text class="tn-icon-right option-arrow"></text>
          </view>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
// 导入广告助手工具类
import adHelper from '@/utils/adHelper.js';
import unlockConfigService from '@/api/config/unlockConfig.js';
import storageKeys from '@/utils/storage-keys.js';

export default {
  name: 'UnlockMessageModal',
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    targetUserId: {
      type: [String, Number],
      default: ''
    },
    // 场景ID，用于确定使用哪个解锁配置
    sceneId: {
      type: String,
      default: 'default'
    }
  },
  data() {
    return {
      // 分享相关
      shareTimestamp: 0,
      // 解锁配置
      unlockConfig: {
        title: '解锁功能',
        description: '通过完成任务解锁功能',
        video: {
          enabled: true,
          dailyLimit: 3
        },
        share: {
          enabled: true,
          dailyLimit: 1
        },
        vip: {
          enabled: true,
          description: '畅享无限功能'
        },
        extraOptions: []
      }
    }
  },
  computed: {
    // 计算今日剩余的视频解锁次数
    videoUnlockRemaining() {
      this.checkAndResetUnlockCount(); // 检查并重置计数
      const count = uni.getStorageSync(storageKeys.getVideoUnlockKey(this.sceneId)) || 0;
      return Math.max(0, this.unlockConfig.video.dailyLimit - count);
    },

    // 计算今日剩余的分享解锁次数
    shareUnlockRemaining() {
      this.checkAndResetUnlockCount(); // 检查并重置计数
      const count = uni.getStorageSync(storageKeys.getShareUnlockKey(this.sceneId)) || 0;
      return Math.max(0, this.unlockConfig.share.dailyLimit - count);
    }
  },
  created() {
    // 加载场景对应的解锁配置
    this.loadUnlockConfig();
  },
  methods: {
    // 加载解锁配置
    async loadUnlockConfig() {
      try {
        const config = await unlockConfigService.getUnlockConfig(this.sceneId);
        if (config) {
          this.unlockConfig = Object.assign({}, this.unlockConfig, config);
        }
      } catch (error) {
        console.error('加载解锁配置失败:', error);
        // 使用默认配置
      }
    },

    // 处理额外选项点击
    handleExtraOptionClick(option) {
      if (option.action && typeof option.action === 'string') {
        if (this[option.action] && typeof this[option.action] === 'function') {
          this[option.action](option);
        }
      } else {
        // 通知父组件处理自定义选项
        this.$emit('extra-option-click', option);
      }
    },

    // 关闭弹窗
    closeModal() {
      this.$emit('close');
    },

    // 显示VIP弹窗
    showVipModal() {
      this.$emit('show-vip');
      // this.closeModal();
    },

    // 通过观看激励视频解锁
    unlockByVideo() {
      if (this.videoUnlockRemaining <= 0) {
        uni.showToast({
          title: '今日解锁次数已用完',
          icon: 'none'
        });
        return;
      }

      // 使用广告助手显示广告
      adHelper.showAdConfirm(
        '解锁私信功能',
        '观看完整视频广告即可解锁私信功能',
        // 成功回调
        () => {
          this.completeVideoUnlock();
        },
        // 失败回调
        (err) => {
          console.error('广告显示失败:', err);

          if (typeof err === 'string' && err === '用户未完整观看广告') {
            uni.showToast({
              title: '需要观看完整广告才能解锁',
              icon: 'none'
            });
            return;
          }

          // 显示错误提示，并询问是否直接解锁
          uni.showModal({
            title: '提示',
            content: '广告加载失败，是否直接解锁？',
            success: res => {
              if (res.confirm) {
                this.completeVideoUnlock();
              }
            }
          });
        }
      );
    },

    // 完成视频解锁
    completeVideoUnlock() {
      // 增加视频解锁计数
      const videoUnlockKey = storageKeys.getVideoUnlockKey(this.sceneId);
      const count = uni.getStorageSync(videoUnlockKey) || 0;
      uni.setStorageSync(videoUnlockKey, count + 1);

      // 保存当前日期
      const lastUnlockDateKey = storageKeys.getLastUnlockDateKey(this.sceneId);
      uni.setStorageSync(lastUnlockDateKey, this.getCurrentDate());

      // 解锁成功
      this.unlockSuccess();
    },

    // 通过分享解锁
    unlockByShare() {
      if (this.shareUnlockRemaining <= 0) {
        uni.showToast({
          title: '今日分享解锁次数已用完',
          icon: 'none'
        });
        return;
      }

      // #ifndef MP-WEIXIN
      // 非微信小程序环境，使用系统分享
      uni.share({
        provider: "weixin",
        scene: "WXSceneSession",
        type: 0,
        title: "和我一起加入游戏社交",
        summary: "这里有最好玩的游戏和最有趣的玩家",
        imageUrl: "/static/images/share-image.png",
        success: res => {
          this.completeShareUnlock();
        },
        fail: err => {
          console.error('分享失败:', err);
          // 分享失败也允许解锁
          this.completeShareUnlock();
        }
      });
      // #endif
    },

    // 准备分享（微信小程序环境）
    prepareShare() {
      if (this.shareUnlockRemaining <= 0) {
        uni.showToast({
          title: '今日分享解锁次数已用完',
          icon: 'none'
        });
        return;
      }

      // 记录分享时间戳
      this.shareTimestamp = Date.now();

      // 通知父页面准备分享解锁
      this.$emit('prepare-share', {
        timestamp: this.shareTimestamp,
        userId: this.targetUserId,
        sceneId: this.sceneId
      });

      // 显示提示
      uni.showToast({
        title: '请分享给好友解锁',
        icon: 'none'
      });
    },

    // 完成分享解锁
    completeShareUnlock() {
      // 增加分享解锁计数
      const shareUnlockKey = storageKeys.getShareUnlockKey(this.sceneId);
      const count = uni.getStorageSync(shareUnlockKey) || 0;
      uni.setStorageSync(shareUnlockKey, count + 1);

      // 保存当前日期
      const lastUnlockDateKey = storageKeys.getLastUnlockDateKey(this.sceneId);
      uni.setStorageSync(lastUnlockDateKey, this.getCurrentDate());

      // 解锁成功
      this.unlockSuccess();
    },

    // 解锁成功
    unlockSuccess() {
      // 显示解锁成功提示
      uni.showToast({
        title: '解锁成功',
        icon: 'success'
      });

      // 通知父组件解锁成功
      this.$emit('unlock-success', {
        userId: this.targetUserId
      });

      // 关闭弹窗
      this.closeModal();
    },

    // 通过金币解锁
    unlockByCoin(option) {
      console.log('通过金币解锁，选项数据:', option);

      // 这里可以添加金币余额检查等逻辑
      // 由于这个方法会被扩展选项系统调用，我们直接发出事件，由父组件处理
      this.$emit('extra-option-click', option);
    },

    // 获取当前日期字符串（年-月-日格式）
    getCurrentDate() {
      const now = new Date();
      const year = now.getFullYear();
      const month = String(now.getMonth() + 1).padStart(2, '0');
      const day = String(now.getDate()).padStart(2, '0');
      return `${year}-${month}-${day}`;
    },

    // 检查并重置解锁计数（如果日期已变更）
    checkAndResetUnlockCount() {
      const lastUnlockDateKey = storageKeys.getLastUnlockDateKey(this.sceneId);
      const lastDate = uni.getStorageSync(lastUnlockDateKey);
      const currentDate = this.getCurrentDate();

      // 如果日期已变更，重置计数
      if (lastDate !== currentDate) {
        const videoUnlockKey = storageKeys.getVideoUnlockKey(this.sceneId);
        const shareUnlockKey = storageKeys.getShareUnlockKey(this.sceneId);

        uni.setStorageSync(videoUnlockKey, 0);
        uni.setStorageSync(shareUnlockKey, 0);
        uni.setStorageSync(lastUnlockDateKey, currentDate);
      }
    }
  }
};
</script>

<style lang="scss" scoped>
.unlock-modal {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  z-index: 9999;

  &-mask {
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background-color: rgba(0, 0, 0, 0.6);
  }

  &-content {
    position: absolute;
    left: 50%;
    top: 50%;
    transform: translate(-50%, -50%);
    width: 580rpx;
    background-color: #fff;
    border-radius: 24rpx;
    overflow: hidden;
    padding-bottom: 40rpx;
  }

  &-header {
    position: relative;
    padding: 30rpx;
    text-align: center;
    border-bottom: 1rpx solid #f5f5f5;
  }

  &-title {
    font-size: 34rpx;
    font-weight: bold;
    color: #333;
  }

  &-close {
    position: absolute;
    right: 30rpx;
    top: 30rpx;
    font-size: 36rpx;
    color: #999;
  }

  &-body {
    padding: 30rpx;
    display: flex;
    flex-direction: column;
    align-items: center;
  }
}

.unlock-icon {
  font-size: 180rpx;
  color: #B3F73C;
  margin-bottom: 30rpx;
  text-shadow: 0 0 20rpx rgba(179, 247, 60, 0.3);
}

.unlock-desc {
  font-size: 28rpx;
  color: #666;
  margin-bottom: 40rpx;
  text-align: center;
}

.unlock-options {
  width: 100%;
}

.unlock-option {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 30rpx 20rpx;
  border-radius: 12rpx;
  margin-bottom: 20rpx;
  background-color: #f8f8f8;

  &:active {
    background-color: #f0f0f0;
  }

  &.vip-option {
    background-color: #FFF9E6;

    .option-icon {
      color: #FF9500;
    }

    .option-title {
      color: #FF9500;
    }
  }

  &.coin-option {
    background-color: #F0F8FF;

    .option-icon {
      color: #FFD700;
    }

    .option-title {
      color: #1E90FF;
    }
  }

  &-button {
    background-color: transparent;
    width: 100%;
    padding: 0;
    margin: 0;
    line-height: normal;
    border: none;
    text-align: left;
    display: flex;
    justify-content: space-between;
    align-items: center;

    &::after {
      border: none;
    }
  }

  .option-content {
    display: flex;
    align-items: center;
  }

  .option-icon {
    font-size: 40rpx;
    color: #3B5CF0;
    margin-right: 20rpx;
  }

  .option-text {
    display: flex;
    flex-direction: column;
  }

  .option-title {
    font-size: 30rpx;
    font-weight: bold;
    color: #333;
    margin-bottom: 6rpx;
  }

  .option-desc {
    font-size: 24rpx;
    color: #999;
  }

  .option-arrow {
    font-size: 32rpx;
    color: #999;
  }
}
</style>
